﻿//////////////////
/// AJAX callbacks
/// IMPORTANT: You must include >> master.js <<
////////////////
function ajaxSaveQuery(shortDesc, longDesc, sqlCode, isPublic, retFunc) {
    Proxy.ajaxSaveQuery(shortDesc, longDesc, sqlCode, isPublic,
        function (result) {
            var json = toJSON(result);
            var oldVal = getQuery(json.short_desc);
            if (oldVal == null) {
                _jsonQueries.push(json);
            }
            // update the internal node
            else {
                oldVal.sql_code = json.sql_code;
                oldVal.long_desc = json.long_desc;
            }
            retFunc(json);
        },
        onError
       );
}

function ajaxSaveTable(tablename, desc, isPublic, retFunc) {
    Proxy.ajaxSaveTable(tablename, desc, isPublic,
        function (result) {
            var json = toJSON(result);
            var oldVal = getTable(json.tablename);
            if (oldVal == null) {
                _jsonTables.push(json);
            }
            // update the internal node
            else {
                oldVal.is_public = json.is_public;
                oldVal.description = json.description;
            }
            retFunc(json);
        },
        onError
       );
}

function ajaxDeleteQuery(shortDesc, retFunc) {
    Proxy.ajaxDeleteQuery(shortDesc,
    function (result) {
        var json = toJSON(result);
        // should evaluate to true if successful, false otherwise
        if (json) {
            for (var x in _jsonQueries) {
                if (_jsonQueries[x].short_desc == shortDesc) {
                    delete _jsonQueries[x];
                    break;
                }
            }
        }
        else {
            alert('unable to delete query');
        }
        retFunc(json);
    },
    onError
   );
}

function ajaxDeleteTable(tablename, retFunc) {
    Proxy.ajaxDeleteTable(tablename,
    function (result) {
        var json = toJSON(result);
        if (json) {
            for (var x in _jsonTables) {
                if (_jsonTables[x].tablename == tablename) {
                    delete _jsonTables[x];
                    break;
                }
            }
        }
        else {
            alert('unable to delete table');
        }
        retFunc(json);
    },
    onError
    );
}

function onError(error) {
    // show error message for 4 seconds highlighted
    showStatus("Error: " + error.Message, 4000, true);
}